package conf

import (
	"encoding/base64"
	"os"
	"path"
	"path/filepath"
	"strings"

	"gitee.com/xxhsjp/x-core/utils/xfiles"

	"gitee.com/xxhsjp/x-core/utils/xcrypto"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)

const secret string = "85ereg2e3iplm9u7"

var Wrapper wrapper

func init() {

	var configFileString string = "./config.yaml"
	var userConfigFile string

	if len(os.Args) > 2 && (os.Args[1] == "-c" || os.Args[1] == "--config") {
		userConfigFile = os.Args[2]
	}

	if userConfigFile == "" {
		configFileExists := xfiles.ExistFile(configFileString)
		if !configFileExists {
			dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
			configFileString = path.Join(dir, "config.yaml")
		}
	} else {
		configFileString = userConfigFile
	}

	logrus.Info("load config file: ", configFileString)

	viper := viper.New()
	viper.SetConfigFile(configFileString)
	if err := viper.ReadInConfig(); err != nil {
		if userConfigFile == "" {
			logrus.Warn("load config file failure: ", err)
		} else {
			logrus.Fatal("process exited because fatal err:: ", err)
		}
	}
	Wrapper = wrapper{viper}
}

type wrapper struct {
	*viper.Viper
}

func (c *wrapper) GetDecryptedString(str string, isVal ...bool) (string, error) {
	var val string
	if len(isVal) > 0 && isVal[0] {
		val = str
	} else {
		val = c.GetString(str)
	}
	prefix := "@=="
	if strings.Index(val, prefix) == 0 {
		val = strings.TrimPrefix(val, prefix)
		decoded, err := base64.StdEncoding.DecodeString(val)
		if err != nil {
			return "", err
		}
		val = string(xcrypto.Aes.DecryptCBC(decoded, []byte(secret)))
	}
	return val, nil
}

func (c *wrapper) GetEncryptedString(decoded string) (string, error) {
	val := xcrypto.Aes.EncryptCBC([]byte(decoded), []byte(secret))
	return "@==" + base64.StdEncoding.EncodeToString(val), nil
}
